﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		CategoryRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            CategoryRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using Dexter.Repository.NHibernate.SessionFactory;
using Topics.Radical.Validation;

namespace Dexter.Repository.NHibernate.Repositories {

	/// <summary>
	/// The implementation of <see cref="ICategoryRepository"/>
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>CategoryRepository</c> type:
	///   <code>
	///       // Create the type.
	///       CategoryRepository ds = new CategoryRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class CategoryRepository : RepositoryBase <Category> , ICategoryRepository {
		/// <summary>
		/// Initializes a new instance of the <see cref="CategoryRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public CategoryRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		#region Implementation of ICategoryRepository

		/// <summary>
		/// Adds the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		public override void Add ( Category item ) {
			this.Save ( item );
		}

		/// <summary>
		/// Removes the specified item.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <returns></returns>
		public override bool Remove ( Category item ) {
			this.DeleteCategory ( item,null );
			return true;
		}

		/// <summary>
		/// Retrieve the defalt category.
		/// </summary>
		/// <returns>An instance of Category.</returns>
		public virtual Category GetDefaultCategory ( ) {
			return GetDefaultCategory ( true );
		}

		/// <summary>
		/// Retrieve the defalt category.
		/// </summary>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>An instance of Category.</returns>
		public virtual Category GetDefaultCategory ( bool enableTracking ) {
			return Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetDefaultCategory )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <Category> ( );
		}

		/// <summary>
		/// Gets the default category with child and parent.
		/// </summary>
		/// <returns>
		/// An instance of Category with all tree loaded
		/// </returns>
		public virtual Category GetDefaultCategoryWithChilds ( ) {
			return GetDefaultCategoryWithChilds ( true );
		}

		/// <summary>
		/// Gets the default category with child and parent.
		/// </summary>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>An instance of Category.</returns>
		public virtual Category GetDefaultCategoryWithChilds ( bool enableTracking ) {
			return Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetDefaultCategoryWithChilds )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <Category> ( );
		}

		/// <summary>
		/// Retrieve a Category by its name.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns>
		/// Null if there isn't a category wich specified name, otherwise an instance of Category.
		/// The Parent and Childs are not fetched.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 0.</exception>
		public virtual Category GetCategoryByKey ( int key ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid category key" );

			return Session.Get <Category> ( key );
		}

		/// <summary>
		/// Retrieve a Category by its name.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns>
		/// Null if there isn't a category wich specified name, otherwise an instance of Category.
		/// The Parent and Childs are not fetched.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 0.</exception>
		public virtual Category GetCategoryByKeyWithChilds ( int key ) {
			return GetCategoryByKeyWithChilds ( key , true );
		}

		/// <summary>
		/// Retrieve a Category by its name.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// Null if there isn't a category wich specified name, otherwise an instance of Category.
		/// The Parent and Childs are not fetched.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="key"/> is lesser than 0.</exception>
		public virtual Category GetCategoryByKeyWithChilds ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid blogroll Key" );

			return Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetCategoryByKeyWithChilds )
				.SetParameter ( "id" , key )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <Category> ( );
		}

		/// <summary>
		/// Retrieve a Category by its name.
		/// </summary>
		/// <param name="name">The name.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// Null if there isn't a category wich specified name, otherwise an instance of Category.
		/// The Parent and Childs are not fetched.
		/// </returns>
		public virtual Category GetCategoryByNameWithChilds(string name, bool enableTracking)
		{
			Ensure.That(name)
				.Named("name")
				.WithPreview((v, e) => Logger.Warn(v.GetFullErrorMessage(), e))
				.IsNotNullNorEmpty()
				.WithMessage("Invalid category name");

			return Session.GetNamedQuery(KnownQueries.CategoryRepository.GetCategoryByNameWithChilds)
				.SetParameter("name", name)
				.SetReadOnly(!enableTracking)
				.UniqueResult<Category>();
		}

		/// <summary>
		/// Deletes the specified category and moved the into into another.
		/// </summary>
		/// <param name="category">The category to delete.</param>
		/// <param name="newCategory">The new category for the posts of the old category.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="category"/> is <c>null</c>.</exception>
		public virtual void DeleteCategory ( Category category, Category newCategory ) {
			Ensure.That ( category )
				.Named ( "category" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid category." );

			newCategory = newCategory ?? GetDefaultCategory ( );

			category.ValidateForDelete ( );

			IList <Post> posts = Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetAllPostsIntoACategory )
				.SetParameter ( "catId" , category.Id )
				.List <Post> ( );

			foreach ( Post post in posts ) {
				post.Categories.Remove ( category );

				if ( !post.Categories.Contains ( newCategory ) ) {
					post.Categories.Add ( newCategory );
				}

				Session.SaveOrUpdate ( post );
			}

			//TODO: it should be different. Take a look the mapping for the inverse relation.
			if (category.Parent != null) {
				category.Parent.Categories.Remove ( category );
				Session.SaveOrUpdate ( category.Parent );
			}

			Session.Delete ( category );
		}

		/// <summary>
		/// Saves the specified category.
		/// </summary>
		/// <param name="category">The category to save.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="category"/> is <c>null</c>.</exception>
		public virtual void Save ( Category category ) {
			Ensure.That ( category )
				.Named ( "category" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid category." );

			category.ValidateForSave ( );

			if ( category.IsDefaultCategory ) {
				Category currentDefault = GetDefaultCategory ( );
				if (currentDefault != null)
				{
					currentDefault.IsDefaultCategory = false;
					Session.SaveOrUpdate(currentDefault);
				}
			}

			Session.SaveOrUpdate ( category );
		}

		/// <summary>
		/// Updates the specified category.
		/// </summary>
		/// <param name="category">The category to update.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="category"/> is <c>null</c>.</exception>
		public virtual void Update ( Category category ) {
			Ensure.That ( category )
				.Named ( "category" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid category." );

			category.ValidateForUpdate ( );
			Session.SaveOrUpdate ( category );
		}

		/// <summary>
		/// Retrurn a flat views of all categories from the repository.
		/// </summary>
		/// <returns>
		/// The return value will never be null, there is always the default category.
		/// The tree il completely loaded.
		/// </returns>
		public virtual IEnumerable<Category> GetCategoriesStructure ( ) {
			return GetCategoriesStructure ( true );
		}

		/// <summary>
		/// Retrurn a strucured views of all categories from the repository.
		/// </summary>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// The return value will never be null, there is always the default category.
		/// The tree il completely loaded.
		/// </returns>
		public virtual IEnumerable<Category> GetCategoriesStructure ( bool enableTracking ) {
			return Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetCategoriesStructureWithChilds )
				.SetReadOnly ( !enableTracking )
				.List <Category> ( );
		}

		///<summary>
		///	Retrurn a strucured views of all categories from the repository.
		///</summary>
		///<returns>
		///	The return value will never be null, there is always the default category.
		///	The tree il completely loaded.
		///</returns>
		public virtual IEnumerable<Category> GetAllCategories ( ) {
			return this.GetAllCategories ( true );
		}

		/// <summary>
		/// Retrurn a flat views of all categories from the repository.
		/// </summary>
		/// <param name = "enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// The return value will never be null, there is always the default category.
		/// The tree il completely loaded.
		/// </returns>
		public virtual IEnumerable<Category> GetAllCategories ( bool enableTracking ) {
			return Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetAllCategoriesWithChilds )
				.SetReadOnly ( !enableTracking )
				.List<Category> ( );
		}

		/// <summary>
		/// This method will update the property <see cref="Category.ContentNumber"/> for each category
		/// </summary>
		public void UpdateCategoryStatistics ( ) {
			var categories = this.GetAllCategories ( true );

			foreach ( var category in categories ) {
				category.ContentNumber = (int)Session.GetNamedQuery ( KnownQueries.CategoryRepository.GetPostCountIntoACategory )
					.SetParameter ( "catId" , category.Id )
					.UniqueResult <long> ( );

				Session.SaveOrUpdate ( category );
			}
		}

		#endregion
	}
}
